package cn.edu.hnu.gpg.service;

import cn.edu.hnu.gpg.dao.TeacherReviewMapper;
import cn.edu.hnu.gpg.entity.*;
import cn.edu.hnu.gpg.entity.enums.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TeacherReviewServiceImpl implements  TeacherReviewService{

    private TeacherReviewMapper teacherReviewMapper;

    private StudentService studentService;
    @Autowired
    TeacherReviewServiceImpl(TeacherReviewMapper teacherReviewMapper){
        this.teacherReviewMapper = teacherReviewMapper;
    }

    //目前存在空指针操作不当，请使用另一个方法
    @Override
    public int createNewReview(User user, byte rating, String comment) {
        if (rating <= 0 || rating > 5)
            return 0;
        if (user == null)
            return 0;
        Student student = studentService.findStudentByUserId(user.getUserId());
        if (student == null)
            return 0;
        return createNewReview(student.getStudentId(),rating,comment);
    }

    @Override
    public int createNewReview(int student_id, byte rating, String comment) {
        if(student_id<1 || rating<=0 || rating>5)
            return 0;

        TeacherReview teacherReview = new TeacherReview();
        teacherReview.setReviewerId(student_id);
        teacherReview.setRating(rating);
        if (!comment.isEmpty())
            teacherReview.setComments(comment);
        return teacherReviewMapper.insertSelective(teacherReview);
    }

    @Override
    public boolean deleteReview(User user) {
        if(user == null || user.getUserType()!= UserType.S)
            return false;

        int student_id = studentService.findStudentByUserId(user.getUserId()).getStudentId();
        TeacherReviewExample teacherReviewExample = new TeacherReviewExample();
        teacherReviewExample.or().andReviewerIdEqualTo(student_id);
        return teacherReviewMapper.deleteByExample(teacherReviewExample) >0 ;
    }

    @Override
    public boolean deleteReview(int student_id) {
        if (student_id < 1)
            return false;

        TeacherReviewExample teacherReviewExample = new TeacherReviewExample();
        teacherReviewExample.or().andReviewerIdEqualTo(student_id);
        return teacherReviewMapper.deleteByExample(teacherReviewExample) >0 ;
    }

    @Override
    public List<TeacherReview> findReviewByUser(int user_id) {
        if (user_id < 1)
            return null;
        int student_id = studentService.findStudentByUserId(user_id).getStudentId();
        TeacherReviewExample teacherReviewExample = new TeacherReviewExample();
        teacherReviewExample.or().andReviewerIdEqualTo(student_id);
        return teacherReviewMapper.selectByExample(teacherReviewExample);
    }
}
